<template>
  <!-- 下拉按钮组件 -->
  <el-dropdown trigger="click"  placement="bottom" @command="handleExport">
    <!-- 主按钮 -->
    <el-button type="primary">
      导出数据<i class="el-icon-arrow-down el-icon--right"></i>
    </el-button>
    
    <!-- 下拉菜单 -->
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item command="excel">
        <i class="el-icon-document"></i> Excel
      </el-dropdown-item>
      <el-dropdown-item command="csv">
        <i class="el-icon-document"></i> CSV
      </el-dropdown-item>
      <el-dropdown-item command="pdf" divided>
        <i class="el-icon-printer"></i> PDF
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
export default {
  props: {
    tableData: Array,    // 必传：表格数据
    columns: Array,      // 必传：列配置[{prop, label}]
    fileName: String     // 可选：自定义文件名
  },
  methods: {
    // 选择导出格式时触发
    async handleExport(format) {
      try {
        this.$message.info(`正在生成${format.toUpperCase()}文件...`)
        
        switch(format) {
          case 'excel': await this.exportExcel(); break
          case 'csv': await this.exportCSV(); break
          case 'pdf': await this.exportPDF(); break
        }
        
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error(`导出失败: ${error}`)
      }
    },

    /* 核心导出方法 */
    // 1. 导出Excel
    exportExcel() {
      return new Promise((resolve) => {
        const XLSX = require('xlsx')
        const ws = XLSX.utils.json_to_sheet(this.processedData)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        XLSX.writeFile(wb, `${this.filename}.xlsx`)
        resolve()
      })
    },
    
    // 2. 导出CSV
    exportCSV() {
      const headers = this.columns.map(c => `"${c.label.replace(/"/g, '""')}"`).join(',')
      const rows = this.tableData.map(item => 
        this.columns.map(col => `"${String(item[col.prop] || '').replace(/"/g, '""')}"`).join(',')
      ).join('\n')
      
      const blob = new Blob(["\uFEFF" + headers + '\n' + rows], { type: 'text/csv' })
      this.download(blob, `${this.filename}.csv`)
    },
    
    // 3. 导出PDF
    exportPDF() {
      return new Promise((resolve) => {
        import('jspdf').then(jsPDF => {
          import('html2canvas').then(html2canvas => {
            const table = document.querySelector('.el-table')
            html2canvas(table).then(canvas => {
              const pdf = new jsPDF.default('landscape')
              const imgData = canvas.toDataURL('image/png')
              const imgWidth = 280 // A4纸宽度
              const imgHeight = canvas.height * imgWidth / canvas.width
              pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight)
              pdf.save(`${this.filename}.pdf`)
              resolve()
            })
          })
        })
      })
    },
    
    /* 工具方法 */
    download(blob, filename) {
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = filename
      link.click()
      URL.revokeObjectURL(link.href)
    },
    
    get processedData() {
      return this.tableData.map(row => {
        const item = {}
        this.columns.forEach(col => {
          item[col.label] = row[col.prop]
        })
        return item
      })
    },
    
    get filename() {
      return this.fileName || `export_${new Date().getTime()}`
    }
  }
}
</script>